import { HubConnection, HubConnectionBuilder, LogLevel } from '@microsoft/signalr'

// 类型定义
export interface ProportionItem {
  name: string
  value: number
  color: string
}

export interface InventoryProportionData {
  timestamp: string
  quantityData: ProportionItem[]
  amountData: ProportionItem[]
  totalQuantity: number
  totalAmount: number
}

export interface StatisticsItem {
  date: string
  quantity: number
  amount: number
  count: number
}

export interface StatisticsSummary {
  totalQuantity: number
  totalAmount: number
  totalCount: number
  avgQuantity: number
  avgAmount: number
}

export interface InboundStatisticsData {
  timestamp: string
  timeRange: string
  chartData: StatisticsItem[]
  summary: StatisticsSummary
}

export interface OutboundStatisticsData {
  timestamp: string
  timeRange: string
  chartData: StatisticsItem[]
  summary: StatisticsSummary
}

export interface RankingItem {
  rank: number
  productId: number
  productName: string
  quantity: number
  amount: number
  count: number
}

export interface RankingData {
  timestamp: string
  inboundRanking: RankingItem[]
  outboundRanking: RankingItem[]
}

export interface SystemMessage {
  id: string
  type: 'info' | 'warning' | 'error' | 'success'
  title: string
  content: string
  timestamp: string
  autoClose: boolean
  data: Record<string, any>
}

// SignalR服务类
class DashboardSignalRService {
  private connection: HubConnection | null = null
  private isConnecting = false
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectInterval = 5000

  // 事件回调
  private onInventoryProportionCallback: ((data: InventoryProportionData) => void) | null = null
  private onInboundStatisticsCallback: ((data: InboundStatisticsData) => void) | null = null
  private onOutboundStatisticsCallback: ((data: OutboundStatisticsData) => void) | null = null
  private onRankingDataCallback: ((data: RankingData) => void) | null = null
  private onSystemMessagesCallback: ((messages: SystemMessage[]) => void) | null = null
  private onConnectionStateChangeCallback: ((state: string) => void) | null = null

  constructor() {
    this.connection = new HubConnectionBuilder()
      .withUrl('http://123.56.75.137:8006/dashboardRealtimeHub')
      .configureLogging(LogLevel.Information)
      .withAutomaticReconnect()
      .build()

    this.setupEventHandlers()
  }

  private setupEventHandlers() {
    if (!this.connection) return

    // 设置接收事件
    this.connection.on('ReceiveInventoryProportion', (data: InventoryProportionData) => {
      if (this.onInventoryProportionCallback) {
        this.onInventoryProportionCallback(data)
      }
    })

    this.connection.on('ReceiveInboundStatistics', (data: InboundStatisticsData) => {
      if (this.onInboundStatisticsCallback) {
        this.onInboundStatisticsCallback(data)
      }
    })

    this.connection.on('ReceiveOutboundStatistics', (data: OutboundStatisticsData) => {
      if (this.onOutboundStatisticsCallback) {
        this.onOutboundStatisticsCallback(data)
      }
    })

    this.connection.on('ReceiveRankingData', (data: RankingData) => {
      if (this.onRankingDataCallback) {
        this.onRankingDataCallback(data)
      }
    })

    // 系统消息处理 - 支持单条和多条消息
    this.connection.on('ReceiveSystemMessage', (message: SystemMessage) => {
      if (this.onSystemMessagesCallback) {
        this.onSystemMessagesCallback([message])
      }
    })

    this.connection.on('ReceiveSystemMessages', (messages: SystemMessage[]) => {
      if (this.onSystemMessagesCallback) {
        this.onSystemMessagesCallback(messages)
      }
    })

    // 连接状态变化
    this.connection.onreconnecting(() => {
      if (this.onConnectionStateChangeCallback) {
        this.onConnectionStateChangeCallback('Reconnecting')
      }
    })

    this.connection.onreconnected(() => {
      if (this.onConnectionStateChangeCallback) {
        this.onConnectionStateChangeCallback('Connected')
      }
      this.reconnectAttempts = 0
    })

    this.connection.onclose(() => {
      if (this.onConnectionStateChangeCallback) {
        this.onConnectionStateChangeCallback('Disconnected')
      }
    })
  }

  async connect(): Promise<boolean> {
    if (!this.connection || this.isConnecting) {
      return false
    }

    try {
      this.isConnecting = true
      console.log('正在连接SignalR服务...', 'http://123.56.75.137:8006/dashboardRealtimeHub')
      await this.connection.start()
      console.log('SignalR连接成功')
      if (this.onConnectionStateChangeCallback) {
        this.onConnectionStateChangeCallback('Connected')
      }
      return true
    } catch (error) {
      console.error('SignalR连接失败:', error)
      if (this.onConnectionStateChangeCallback) {
        this.onConnectionStateChangeCallback('Disconnected')
      }
      return false
    } finally {
      this.isConnecting = false
    }
  }

  async disconnect(): Promise<void> {
    if (this.connection) {
      try {
        await this.connection.stop()
        console.log('SignalR连接已断开')
      } catch (error) {
        console.error('断开SignalR连接失败:', error)
      }
    }
  }

  async requestLatestData(): Promise<void> {
    if (this.connection && this.connection.state === 'Connected') {
      try {
        await this.connection.invoke('JoinDashboardGroup')
        console.log('已加入仪表板组')
      } catch (error) {
        console.error('加入仪表板组失败:', error)
      }
    }
  }

  // 事件监听器设置方法
  onInventoryProportion(callback: (data: InventoryProportionData) => void) {
    this.onInventoryProportionCallback = callback
  }

  onInboundStatistics(callback: (data: InboundStatisticsData) => void) {
    this.onInboundStatisticsCallback = callback
  }

  onOutboundStatistics(callback: (data: OutboundStatisticsData) => void) {
    this.onOutboundStatisticsCallback = callback
  }

  onRankingData(callback: (data: RankingData) => void) {
    this.onRankingDataCallback = callback
  }

  onSystemMessages(callback: (messages: SystemMessage[]) => void) {
    this.onSystemMessagesCallback = callback
  }

  onConnectionStateChange(callback: (state: string) => void) {
    this.onConnectionStateChangeCallback = callback
  }

  // 获取连接状态
  getConnectionState(): string {
    return this.connection?.state || 'Disconnected'
  }
}

// 创建单例实例
const dashboardSignalRService = new DashboardSignalRService()

export default dashboardSignalRService
